package com.sigmazero13.MKDummy.components;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import com.sigmazero13.MKDummy.R;
import com.sigmazero13.MKDummy.models.CardDeck;

public class CardDisplayIconRemainingView extends CardDisplayView {
	
	int remaining = 0;
	Bitmap cardImg;
	View drawView;

	public CardDisplayIconRemainingView(Context c) {
		super(c);
		
		commonSetup(c);
	}

	public CardDisplayIconRemainingView(Context c, AttributeSet attrs) {
		super(c, attrs);
		
		commonSetup(c);
	}
	
	
	@Override
	public void onDeckChanged(CardDeck deck) {
		remaining = deck.countCardsRemaining();
		drawView.invalidate();
	}	
	
	private void commonSetup(Context c) {
		LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.player_data_draw, this, true);
		
		drawView = new DrawView(c);
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		drawView.setLayoutParams(lp);
		this.addView(drawView);
		
		cardImg = BitmapFactory.decodeResource(getResources(), R.drawable.card_back);
	}
	
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int w = MeasureSpec.getSize(widthMeasureSpec);
		int h = cardImg.getHeight() + 10;
		drawView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(h, MeasureSpec.UNSPECIFIED));
		setMeasuredDimension(w,h);
	}
	
	
	private class DrawView extends View {
		public DrawView(Context c) {
			super(c);
		}
		
		@Override
		public void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			
			if (remaining == 0) return;
			
			int cardWidth = cardImg.getWidth();
			float spacing = cardWidth/3;
			
			float stackWidth = cardWidth + (remaining-1)*spacing;
			
			if (stackWidth > canvas.getWidth()) {
				float leftover = (canvas.getWidth()) - cardWidth;
				spacing = leftover/(remaining-1);
				if (spacing < 1) spacing = 1;
			}
			
			float x = 0;
			for (int i = 0; i < remaining; i++) {
				canvas.drawBitmap(cardImg, x, 5, null);
				x += spacing;
			}
		}
		
		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			int w = MeasureSpec.getSize(widthMeasureSpec);
			int h = MeasureSpec.getSize(heightMeasureSpec);
			setMeasuredDimension(w,h);
		}	
	}
		
}